import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/fund_record_list_entity.dart';

import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class FundRecordLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  var isLoading = true.obs;
  var fundRecords = <FundRecordListData>[].obs;
  var tabTitles = ['全部', '收入', '支出'].obs;
  var bottomTips = ''.obs;
  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  late TabController tabController;
  late ScrollController scrollController;

  final _pageSize = 20;
  int _page = 1;
  int _type = 0;

  @override
  void onInit() {
    super.onInit();

    tabController = TabController(length: tabTitles.length, vsync: this);
    tabController.addListener(() {
      if (tabController.index.toDouble() == tabController.animation?.value) {
        _type = tabController.index;
        reload();
      }
    });

    scrollController = ScrollController();
    scrollController.addListener(() {
      if (scrollController.position.pixels >=
          scrollController.position.maxScrollExtent) {
        _getFundRecords();
      }
    });

    reload();
  }

  void reload() {
    _page = 1;
    fundRecords.clear();
    isLoading.value = true;
    _getFundRecords();
  }

  void onClickRecord(FundRecordListData record) {
    Get.toNamed(RouteGet.fundRecordDetail, arguments: record);
  }

  void _getFundRecords() {
    apiService
        .getFundRecordList(_page, _pageSize, commonService.getRole(), _type)
        .then((response) => {
              isLoading.value = false,
              _page++,
              if (response != null)
                {
                  fundRecords.addAll(response.data),
                  if (response.data.isEmpty)
                    {
                      bottomTips.value = noMoreTip,
                    }
                  else
                    {
                      bottomTips.value = loadingTip,
                    }
                }
              else
                {
                  bottomTips.value = noMoreTip,
                }
            });
  }
}
